import axios from 'axios'
import qs from 'qs'
import rooter from "@/router"
import { Loading, Message } from 'element-ui'
// 手动创建一个 axios 对象, 参考: https://github.com/axios/axios#creating-an-instance
const request = axios.create({
    // 请求配置参考: https://github.com/axios/axios#request-config
    // 根据不同环境设置 baseURL, 最终发送请求时的URL为: baseURL + 发送请求时写URL ,
    // 比如 get('/test'), 最终发送请求是: /dev-api/test
    // baseURL: '/dev-api',
    baseURL: process.env.VUE_APP_BASE_API,
    timeout: 10000 // 请求超时
})

const loading = {
	loadingInstance : null, // Loading实例
	open: function () { // 打开加载
		console.log('加载中', this.loadingInstance)
		if(this.loadingInstance === null) { // 创建单例, 防止切换路由重复加载
			//console.log('创建加载实例..')
			this.loadingInstance = Loading.service({
				text: '拼命加载中',
				target: '.main', // 效果显示区域
				background: 'rgba(0, 0, 0, 0.5)' // 加载效果
			})
		}
	},
	close: function() { // 关闭加载
		if(this.loadingInstance !== null){
			this.loadingInstance.close()
			//console.log('结束加载')
		}
		this.loadingInstance = null // 关闭后实例重新赋值null, 下次让它重新创建
	}
}
/**
 * 添加一个全局的请求拦截器
 */
request.interceptors.request.use(function(config) {
	loading.open();//打开加载效果
	//console.log("localstorge"+localStorage.getItem('Authorization'))
    if (localStorage.getItem('Authorization')) { //为每个请求添加一个Token参数
        config.headers['Authorization'] = localStorage.getItem('Authorization');
    } 
    return config;
}, function(error) {
	loading.close();//关闭加载效果
    return Promise.reject(error);
});

/**
 * 添加一个全局的响应拦截器
 */
request.interceptors.response.use(function(resp) {
	loading.close();
    return resp.data;
}, function(error) {
	loading.close();
    return Promise.reject(error);
});
// ------------------------------------封装数据返回失败提示函数-------------------------------------
function errorState(response) {
    //console.log("axios error:" + response)
	if(response.code!=null && response.code!='' && response.code!=undefined && response.code == "401"){
		localStorage.removeItem('Authorization');//设置用户的Token令牌为空
		localStorage.removeItem('SYSTEM_USER'); 
		rooter.push("login");
	}
    return response;
}

// ------------------------------------封装数据返回成功提示函数-------------------------------------
function successState(res) {
	//console.log("axios success:" + res.data.code)
    if (res.code === '401') {
        localStorage.removeItem('Authorization');//设置用户的Token令牌为空
        localStorage.removeItem('SYSTEM_USER');
        rooter.push("login");
    }
	 return res;
}

function Axios(method, url, params){
    const req = request({
        url:url,
        method:method,
        params: method === 'GET' || method === 'DELETE' ? params : null,
		data: method === 'POST' || method === 'PUT' ? qs.stringify(params) : null
    }).catch(error => {
        console.log(error);
    });
	
	var a = new Promise((resolve, reject)=>{
		req.then((res) => {
		    var b =successState(res)
			return resolve(b)
		}).catch((response) => {
			var b =errorState(response)
			reject(b)
		})
	});
	return a
	
}


export default{
    install: function(Vue) {
        Vue.prototype.getAxios = (url, params) => Axios('GET', url, params)
        Vue.prototype.postAxios = (url, params) => Axios('POST', url, params)
        Vue.prototype.putAxios = (url, params) => Axios('PUT', url, params)
        Vue.prototype.deleteAxios = (url, params) => Axios('DELETE', url, params)
    }

}